package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.utils.UserThreadLocalUtil;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;
import com.sky.vo.PageResult;
import com.sky.vo.SetmealVO;
import io.netty.handler.codec.MessageAggregationException;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * PROJECT_NAME: sky-take-out
 * NAME: SetmealServiceImpl
 *
 * @AUTHOR: zhang
 * DATE: 2023/11/24
 * DESCRIPTION :
 */
@Service
public class SetmealServiceImpl implements SetmealService {
    @Resource
    private SetmealMapper setmealMapper;
    @Resource
    private SetmealDishMapper setmealDishMapper;
    @Resource
    private DishMapper dishMapper;
    /**
     * 套餐分页
     * @param pageQueryDTO
     * @return
     */
    @Override
    public Result<PageResult> getPage(SetmealPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<SetmealVO> pageReault = setmealMapper.getPage(pageQueryDTO);
        PageResult result = PageResult.builder().total(pageReault.getTotal()).records(pageReault.getResult()).build();
        return Result.success(result);
    }

    /**
     * 新增套餐
     * @param setmealDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertSetmeal(SetmealDTO setmealDTO) {
        //1.添加套餐基本信息
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        //补齐字段
        setmeal.setCreateTime(LocalDateTime.now());
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setCreateUser(UserThreadLocalUtil.getUser());
        setmeal.setUpdateUser(UserThreadLocalUtil.getUser());
        //入库
        setmealMapper.insert(setmeal);

        //2.添加套餐菜品关联信息
        List<SetmealDish> setmealDishList = setmealDTO.getSetmealDishes();
        if(!Objects.isNull(setmealDishList)){
            Long setmealId = setmeal.getId();
            setmealDishMapper.insertSetmealDish(setmealDishList,setmealId);
        }
    }

    /**
     * 删除套餐
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSetmeal(List<Long> ids) {
        //根据id查询套餐状态
        for (Long setmealId : ids) {
            Setmeal setmeal = setmealMapper.selectSetmeal(setmealId);
            Integer status = setmeal.getStatus();
            //起售中的套餐不能删除
            if (status.equals(StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }
        //批量删除套餐信息
        setmealMapper.batchDelete(ids);
        //批量删除套餐关联的菜品
        setmealDishMapper.batchDeleteSetmealDish(ids);
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public SetmealVO getSetmealById(Long id) {
        //1.根据套餐id查询套餐基本信息
        Setmeal setmeal = setmealMapper.selectSetmeal(id);
        //2.根据套餐id查询套餐关联的菜品信息
        List<SetmealDish> setmealDishList = setmealDishMapper.selectSetmealDishBySetmealId(id);

        //3.返回数据
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal,setmealVO);
        setmealVO.setSetmealDishes(setmealDishList);
        return setmealVO;
    }

    /**
     * 修改套餐
     * @param setmealDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSetmeal(SetmealDTO setmealDTO) {
        //修改套餐基本信息
        Setmeal setmeal  = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmealMapper.updateSetmeal(setmeal);
        //删除套餐菜品信息
        setmealDishMapper.deleteSetmealDishBySetmealId(setmealDTO.getId());
        //添加套餐菜品信息
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if (Objects.nonNull(setmealDishes)){
            Long setmealId = setmealDTO.getId();
            setmealDishMapper.insertSetmealDish(setmealDishes,setmealId);
        }
    }

    /**
     * 修改套餐状态
     * @param status
     * @param id
     */
    @Override
    public void updateSetmealStatus(Integer status, Long id) {
        //根据套餐id查询套餐状态
        Setmeal setmeal = setmealMapper.selectSetmeal(id);
        Integer setmealStatus = setmeal.getStatus();
        //如果是启用修改为禁用
        if(setmealStatus.equals(StatusConstant.ENABLE)){
            //禁用
            setmeal.setStatus(StatusConstant.DISABLE);
            setmealMapper.update(setmeal);
            //如果是禁用修改为启用
        }else if (setmealStatus.equals(StatusConstant.DISABLE)){
            //起售（套餐关联的菜品都是启售状态，才可以启售）
            //根据套餐id查询关联表
            List<SetmealDish> setmealDishList = setmealDishMapper.selectSetmealDishBySetmealId(id);
            if (Objects.nonNull(setmealDishList)){
                for (SetmealDish setmealDish : setmealDishList) {
                    //获取菜品id,查询菜品的状态
                    Long dishId = setmealDish.getDishId();
                    DishVO dishVO = dishMapper.selectDishById(dishId);
                    if (dishVO==null){
                        throw new SetmealEnableFailedException("套餐包含的菜品信息不存在");
                    }
                    if (dishVO.getStatus().equals(StatusConstant.DISABLE)){
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                }
            }
            setmeal.setStatus(StatusConstant.ENABLE);
            setmealMapper.update(setmeal);
        }

    }

    /**
     * 根据分类id查询套餐列表
     * @param setmeal (分类id+状态：启用)
     * @return
     */
    @Override
    public List<Setmeal> selectSetmealByCategoryId(Setmeal setmeal) {
        //根据分类id查询套餐列表
        return setmealMapper.selectSetmealByCategoryId(setmeal);
    }

    /**
     * 根据套餐id查询套餐包含的菜品
     * @param setmealId
     * @return
     */
    @Override
    public List<DishItemVO> selectSetmealDishBySetmealId(Long setmealId) {
        //要返回的信息集合
        List<DishItemVO> dishItemVOList = new ArrayList<>();
        //查询套餐包含的菜品
        List<SetmealDish> setmealDishList = setmealDishMapper.selectSetmealDishBySetmealId(setmealId);

        for (SetmealDish setmealDish : setmealDishList) {
            DishItemVO dishItemVO = new DishItemVO();
            //获取菜品份数
            Integer copies = setmealDish.getCopies();
            //菜品名称
            String name = setmealDish.getName();
            //将数据保存到dishItemVO中用于返回
            dishItemVO.setCopies(copies);
            dishItemVO.setName(name);
            //获取菜品id,用于查询菜品信息
            Long dishId = setmealDish.getDishId();
            DishVO dishVO = dishMapper.selectDishById(dishId);
            //获取菜品描述
            String description = dishVO.getDescription();
            //获取菜品图片地址
            String imageURL = dishVO.getImage();
            dishItemVO.setDescription(description);
            dishItemVO.setImage(imageURL);
            dishItemVOList.add(dishItemVO);
        }
        return dishItemVOList;
    }
}
